package cron

import (
	"fmt"
	"github.com/robfig/cron/v3"
	"github.com/vueadmin/app/cron/internal/logic"
	"github.com/vueadmin/app/cron/internal/svc"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	"time"
)

type Task struct {
	Name string                    //任务名称
	Rule string                    //任务规则
	Url  string                    //url访问地址
	Fun  func(*svc.ServiceContext) //消费者执行方法
}

// 消费者执行列表
var cronList = []*Task{
	{Name: "测试任务", Rule: "*/10 * * * * ?", Fun: logic.Demo}, //10秒执行一次
}

// 启动定时任务
func StartCron(svcCtx *svc.ServiceContext) {
	nyc, _ := time.LoadLocation("Asia/Shanghai")
	secondParser := cron.NewParser(cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor)
	conn := cron.New(cron.WithParser(secondParser), cron.WithChain(), cron.WithLocation(nyc))

	for _, val := range cronList {
		task := val
		conn.AddFunc(val.Rule, func() {
			if task.Url != "" {
				utils.NewHttpRequest().Request("GET", task.Url, nil)
			} else {
				task.Fun(svcCtx)
			}
			svcCtx.Log.Info(fmt.Sprintf("%s-执行情况:", task.Name), conv.NowDateTime())
		})
	}
	conn.Start()
}
